package cn.supermarket.system.service.impl;

import cn.supermarket.common.contant.CacheConstants;
import cn.supermarket.common.contant.UserConstants;
import cn.supermarket.common.core.text.Convert;
import cn.supermarket.common.exception.ServiceException;
import cn.supermarket.common.utils.CaffeineUtils;
import cn.supermarket.common.utils.JsonUtils;
import cn.supermarket.common.utils.StringUtils;
import cn.supermarket.system.dto.SysConfigDTO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.supermarket.common.entity.system.SysConfig;
import cn.supermarket.system.service.SysConfigService;
import cn.supermarket.system.mapper.SysConfigMapper;
import com.github.benmanes.caffeine.cache.LoadingCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 *
 */
@Service
public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig>
    implements SysConfigService
{
    @Autowired
    private LoadingCache sysConfigCache;

    /**
     * 项目启动时，初始化参数到缓存
     */
    @PostConstruct
    public void init()
    {
        loadingConfigCache();
    }

    /**
     * 加载参数缓存数据
     */
    @Override
    public void loadingConfigCache()
    {
        List<SysConfig> configsList = this.baseMapper.selectList(null);
        for (SysConfig config : configsList)
        {
            CaffeineUtils.put(sysConfigCache,getCacheKey(config.getConfigKey()), config.getConfigValue());
        }
    }

    /**
     * 获取验证码开关
     *
     * @return true开启，false关闭
     */
    @Override
    public boolean selectCaptchaEnabled() {
        String captchaEnabled = selectConfigByKey("sys.account.captchaEnabled");
        if (StringUtils.isEmpty(captchaEnabled))
        {
            return true;
        }
        return Convert.toBool(captchaEnabled);
    }

    /**
     * 根据键名查询参数配置信息
     *
     * @param configKey 参数key
     * @return 参数键值
     */
    @Override
    public String selectConfigByKey(String configKey)
    {
        String configValue = Convert.toStr(CaffeineUtils.get(sysConfigCache,getCacheKey(configKey)));
        if (StringUtils.isNotEmpty(configValue))
        {
            return configValue;
        }
        SysConfig config = new SysConfig();
        config.setConfigKey(configKey);
        SysConfig retConfig = this.baseMapper.selectConfig(config);
        if (StringUtils.isNotNull(retConfig))
        {
            CaffeineUtils.put(sysConfigCache,getCacheKey(configKey),retConfig.getConfigValue());
            return retConfig.getConfigValue();
        }
        return StringUtils.EMPTY;
    }

    /**
     * 根据参数编码，获取value的Object对象
     *
     * @param paramCode 参数编码
     * @param clazz     Object对象
     */
    @Override
    public <T> T getValueObject(String paramCode, Class<T> clazz) {
        String paramValue = selectConfigByKey(paramCode);
        if (org.apache.commons.lang3.StringUtils.isNotBlank(paramValue)) {
            return JsonUtils.parseObject(paramValue, clazz);
        }
        try {
            return clazz.newInstance();
        } catch (Exception e) {
            throw new ServiceException("获取参数错误");
        }
    }

    /**
     * 查询参数配置列表
     *
     * @param config 参数配置信息
     * @return 参数配置集合
     */
    @Override
    public List<SysConfig> selectConfigList(SysConfigDTO config) {
        return this.baseMapper.selectConfigList(config);
    }

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    private String getCacheKey(String configKey)
    {
        return CacheConstants.SYS_CONFIG_KEY + configKey;
    }

    /**
     * 校验参数键名是否唯一
     *
     * @param config 参数配置信息
     * @return 结果
     */
    @Override
    public boolean checkConfigKeyUnique(SysConfig config)
    {
        Long configId = StringUtils.isNull(config.getConfigId()) ? -1L : config.getConfigId();
        SysConfig info = this.baseMapper.checkConfigKeyUnique(config.getConfigKey());
        if (StringUtils.isNotNull(info) && info.getConfigId().longValue() != configId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 批量删除参数信息
     *
     * @param configIds 需要删除的参数ID
     */
    @Override
    public void deleteConfigByIds(Long[] configIds)
    {
        for (Long configId : configIds)
        {
            SysConfig config = this.baseMapper.selectById(configId);
            if (StringUtils.equals(UserConstants.YES, config.getConfigType()))
            {
                throw new ServiceException(String.format("内置参数【%1$s】不能删除 ", config.getConfigKey()));
            }
            this.baseMapper.deleteById(configId);
            CaffeineUtils.remove(sysConfigCache,getCacheKey(config.getConfigKey()));
        }
    }

    /**
     * 重置参数缓存数据
     */
    @Override
    public void resetConfigCache()
    {
        clearConfigCache();
        loadingConfigCache();
    }

    /**
     * 清空参数缓存数据
     */
    @Override
    public void clearConfigCache()
    {
        CaffeineUtils.getAllKeyValues(sysConfigCache);
    }
}




